package com.windoent.yugioh.ui.activity.registlogin;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.baidu.mobstat.StatService;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.windoent.yugioh.AppManager;
import com.windoent.yugioh.BuildConfig;
import com.windoent.yugioh.MainActivity;
import com.windoent.yugioh.R;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.CityAllBean;
import com.windoent.yugioh.bean.GeneralBean;
import com.windoent.yugioh.bean.QQVerifyOneBean;
import com.windoent.yugioh.bean.VerifyQQBean;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.help.db.City;
import com.windoent.yugioh.help.db.DBHelpUtils;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.ExitStackUtils;
import com.windoent.yugioh.utils.LogUtils;
import com.windoent.yugioh.utils.PinyinUtils;
import com.windoent.yugioh.utils.SharedPreUtil;
import com.windoent.yugioh.utils.TextPinyinUtil;
import com.windoent.yugioh.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.functions.Consumer;
import okhttp3.Call;

import static com.windoent.yugioh.constants.Constants.APP_ID;

/**
 * author : robert
 * date   : 2021/4/27 10:34
 * desc   :登录
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout llJump;
    private EditText etCellphone;
    private ImageView ivDelete;
    private Button btnGetCode;
    private LinearLayout tvAgreenment;
    private CheckBox checkPrivacy;
    private TextView tvUserAgree;
    private TextView tvPrivacyAgree;
    private TextView tvEmail;
    private ImageView ivWechat;
    private ImageView ivQq;
    private MessageReceiver messageReceiver;
    private View mView;


    @Override
    public int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        super.initView();
        AppManager.getAppManager().addActivity(this);
        mView = (View) findViewById(R.id.view);
        immersiveStatusBar(mView);
        llJump = (LinearLayout) findViewById(R.id.ll_jump);
        etCellphone = (EditText) findViewById(R.id.et_cellphone);
        ivDelete = (ImageView) findViewById(R.id.iv_delete);
        btnGetCode = (Button) findViewById(R.id.btn_get_code);
        tvAgreenment = (LinearLayout) findViewById(R.id.tv_agreenment);
        checkPrivacy = (CheckBox) findViewById(R.id.check_privacy);
        tvUserAgree = (TextView) findViewById(R.id.tv_user_agree);
        tvPrivacyAgree = (TextView) findViewById(R.id.tv_privacy_agree);
        tvEmail = (TextView) findViewById(R.id.tv_email);
        ivWechat = (ImageView) findViewById(R.id.iv_wechat);
        ivQq = (ImageView) findViewById(R.id.iv_qq);
    }

    @Override
    public void initData() {
        super.initData();
        ivDelete.setVisibility(View.GONE);
        regToWx();
        registerAliasReceiver();
        //数据库
//        getCity();
    }

    private void getCity() {
        OkHttpUtils.get().url("http://42.192.190.38:8081/address?type=all").build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                if (BaseUtils.isJSONValid(response)) {
                    CityAllBean fromJson = gson.fromJson(response, CityAllBean.class);
                    CityAllBean.DataBean data = fromJson.getData();
                    List<CityAllBean.DataBean.ResBean> res = data.getRes();
                    List<City> resBeans = sortByPinYinHeadChar(res);
                    String group = group(resBeans);
                    LogUtils.d("group-->" + group);
                }
            }
        });
    }

    private String group(List<City> resBeans) {
        HashMap<String, List<City>> map = new HashMap<>();
        List<City> list = new ArrayList<>();
        //遍历26个英文字母
        for (Character i = (int) 'A'; i < 'A' + 26; i++) {
            for (int k = 0; k < resBeans.size(); k++) {
                City bean = resBeans.get(k);
                String sort = bean.getSort();
                if (String.valueOf(i).equals(sort)) {
                    City e = new City(bean.getCode(), bean.getId(), bean.getName(), bean.getPinyin(), bean.getSort());
                    list.add(e);
                    DBHelpUtils.insert(mContext, bean.getId(), bean.getName(), bean.getPinyin(), bean.getCode(), bean.getSort());
                }
            }
            map.put(String.valueOf(i), list);
            list = new ArrayList<>();
        }
        return gson.toJson(map);
    }

    public List<City> sortByPinYinHeadChar(List<CityAllBean.DataBean.ResBean> data) {
        List<City> newArrayList = new ArrayList<>();
        for (CityAllBean.DataBean.ResBean arrList : data) {
            String code = arrList.getCode();
            int id = arrList.getId();
            String cityName = arrList.getName();
            //取每个字的首字母
            String pinYinHeadChar;
            if (BaseMethod.notNull(cityName) && cityName.equals("重庆市")) {
                pinYinHeadChar = "C";
            } else
                pinYinHeadChar = PinyinUtils.getFirstLetter(mContext, TextPinyinUtil.getInstance().getPinyin(cityName));
            String pinyin;
            if (BaseMethod.notNull(cityName) && cityName.equals("重庆市")) {
                pinyin = "chongqingshi";
            } else {
                pinyin = TextPinyinUtil.getInstance().getPinyin(cityName);
            }
            City resBean = new City(code, id, cityName, pinyin, pinYinHeadChar);
            if (!newArrayList.contains(resBean)) {
                newArrayList.add(resBean);
            }
        }
        return newArrayList;
    }

    @Override
    public void initListener() {
        super.initListener();
        llJump.setOnClickListener(this);
        ivDelete.setOnClickListener(this);
        btnGetCode.setOnClickListener(this);
        tvUserAgree.setOnClickListener(this);
        tvPrivacyAgree.setOnClickListener(this);
        tvEmail.setOnClickListener(this);
        ivWechat.setOnClickListener(this);
        ivQq.setOnClickListener(this);
        etCellphone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                String string = charSequence.toString().trim();
                ivDelete.setVisibility(BaseMethod.notNull(string) && string.length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        int id = view.getId();
        boolean checked = checkPrivacy.isChecked();
        switch (id) {
            case R.id.ll_jump:
                //跳过
                startActivity(new Intent(mContext, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.iv_delete:
                //删除号码
                etCellphone.setText("");
                break;
            case R.id.btn_get_code:
                //获取验证码
                String s = etCellphone.getText().toString().trim();
                if (BaseMethod.notNull(s) && s.length() > 0) {
                    if (checked) {
                        getCellPhoneCode(s);
                    } else {
                        ToastUtils.showText(getString(R.string.string_check_prvacy_agreement));
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_input_cellphone_please));
                }
                break;
            case R.id.tv_user_agree:
                //用户注册协议
                startActivity(new Intent(mContext, RegistPrivacyActivity.class));
                break;
            case R.id.tv_privacy_agree:
                //隐私条款 PrivacyActivity
                startActivity(new Intent(mContext, PrivacyActivity.class));
                break;
            case R.id.tv_email:
                //邮箱验证
                if (checked) {
                    startActivity(new Intent(mContext, EmailLoginActivity.class));
                } else {
                    ToastUtils.showText(getString(R.string.string_check_prvacy_agreement));
                }
                break;
            case R.id.iv_wechat:
                //微信登录
                rxPermission(0);
                break;
            case R.id.iv_qq:
                //QQ登录
                rxPermission(1);
                break;
            default:
                break;
        }
    }

    //获取手机号验证码
    private void getCellPhoneCode(String cell) {
        showLoadingDialog("");
        PhoneLive.getCellPhoneCode(cell, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                LogUtils.d("response-->" + response);
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GeneralBean generalBean = gson.fromJson(response, GeneralBean.class);
                            ToastUtils.showText(generalBean.getMsg());
                            Intent intent = new Intent(mContext, ObtainCellPhoneCodeActivity.class);
                            intent.putExtra("cell_phone", cell);
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI api;

    private void regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, false);

        // 将应用的appId注册到微信
        api.registerApp(APP_ID);

        //建议动态监听微信启动广播进行注册到微信
/*        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // 将该app注册到微信
                api.registerApp(APP_ID);
            }
        }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));*/

    }

    private void rxPermission(final int type) {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.setLogging(BuildConfig.LOG_DEBUG);
        if (type == 0) {
            //微信
            weixinLogin();
        } else if (type == 1) {
            rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            LogUtils.d("aBoolean:" + aBoolean);
                            if (aBoolean) {
                                if (type == 0) {
                                    //友盟微信
//                                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
                                } else if (type == 1) {
                                    //QQ
                                    UMShareAPI.get(mContext).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, authListener);
                                }
                            } else {
                                ToastUtils.showText(getString(R.string.string_no_permission));
                            }
                        }
                    });
        }
    }

    private void weixinLogin() {
        if (isWXAppInstalledAndSupported()) {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "none";
            api.sendReq(req);
        } else {
            ToastUtils.showText(getString(R.string.string_no_wechat_app_waring));
        }
    }

    //是否安装微信
    private boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Constants.APP_ID);
        return msgApi.isWXAppInstalled();
    }

    //获取登陆成功用户id
    private void registerAliasReceiver() {
        messageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(Constants.MESSAGE_RECEIVED_ALIAS_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, filter);
    }


    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (Constants.MESSAGE_RECEIVED_ALIAS_ACTION.equals(intent.getAction())) {
                    String code = intent.getStringExtra(Constants.WEIXINCODE);
                    LogUtils.d("得到的code：" + code);
                    verifyWexinOne(code);
                }
            } catch (Exception e) {
            }
        }
    }

    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            showLoadingDialog(getString(R.string.string_qq_authing));
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            hideLoadingDialog();
            ToastUtils.showText(getString(R.string.string_souquan_qq_sucess));
            LogUtils.d("zkk-->" + data.toString());
            if (data != null) {
                verifyQQOne(data);
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            hideLoadingDialog();
            ToastUtils.showText(getString(R.string.string_auth_defeat) + t.getMessage());
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            hideLoadingDialog();
            ToastUtils.showText(getString(R.string.string_auth_cancel));
        }
    };

    //第一次验证QQ
    private void verifyQQOne(Map<String, String> data) {
        showLoadingDialog("");
        final String access_token = data.get("access_token");
        final String openid = data.get("openid");
        LogUtils.d("--->:" + access_token + "," + openid);
        PhoneLive.verifyQQOne(openid, "2", new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            QQVerifyOneBean json = gson.fromJson(response, QQVerifyOneBean.class);
                            ToastUtils.showText(json.getMsg());
                            QQVerifyOneBean.DataBean bean = json.getData();
                            if (bean != null) {
                                String user_id = bean.getUser_id();//等于0则需要填写phone
                                if (BaseMethod.notNull(user_id) && user_id.equals("0")) {
                                    Intent intent = new Intent(mContext, BindingCellPhoneActivity.class);
                                    intent.putExtra(Constants.THIRD_TYPE, 1);
                                    intent.putExtra("access_token", access_token);
                                    intent.putExtra("openid", openid);
                                    startActivity(intent);
                                } else {
                                    //TODO
                                    verifyQQTwo(access_token, openid, "", "2", user_id);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //二次验证
    private void verifyQQTwo(String access_token, String open_id, String phone, String appid, String user_id) {
        showLoadingDialog("");
        PhoneLive.verifyQQTwo(access_token, open_id, phone, appid, user_id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                LogUtils.d("response:" + response);
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            VerifyQQBean json = gson.fromJson(response, VerifyQQBean.class);
                            ToastUtils.showText(json.getMsg());
                            VerifyQQBean.DataBean data = json.getData();
                            if (data != null) {
                                String token = data.getToken();
                                LogUtils.d("token:" + token);
                                SharedPreUtil.put(mContext, Constants.APPTOKEN, token);
                                startActivity(new Intent(mContext, MainActivity.class));
                                AppManager.getAppManager().finishAllActivity();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //微信第一次验证
    private void verifyWexinOne(final String code) {
        if (BaseMethod.notNull(code)) {
            showLoadingDialog("");
            PhoneLive.verifyWeixin(code, "1", "", "2", "", new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    hideLoadingDialog();
                    ToastUtils.showText(e.getMessage());
                }

                @Override
                public void onResponse(String response, int id) {
                    hideLoadingDialog();
                    LogUtils.d("lll-->" + response);
                    if (BaseUtils.isJSONValid(response)) {
                        try {
                            if (BaseUtils.codeIs0(mContext, response)) {
                                QQVerifyOneBean json = gson.fromJson(response, QQVerifyOneBean.class);
                                ToastUtils.showText(json.getMsg());
                                QQVerifyOneBean.DataBean data = json.getData();
                                if (data != null) {
                                    String user_id = data.getUser_id();
                                    if (BaseMethod.notNull(user_id) && user_id.equals("0")) {
                                        Intent intent = new Intent(mContext, BindingCellPhoneActivity.class);
                                        intent.putExtra(Constants.THIRD_TYPE, 0);
                                        intent.putExtra("auth_code", code);
                                        startActivity(intent);
                                    } else {
                                        verifyWeixinTwo(code, "2", "", "2", user_id);
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        ToastUtils.showText(getString(R.string.string_response_error));
                    }
                }
            });
        } else {
            ToastUtils.showText(getString(R.string.string_no_code));
        }
    }

    //微信第二次验证
    private void verifyWeixinTwo(String code, String mode, String phone, String appid, String user_id) {
        showLoadingDialog("");
        PhoneLive.verifyWeixin(code, mode, phone, appid, user_id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                LogUtils.d("weixnresponse:" + response);
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            VerifyQQBean json = gson.fromJson(response, VerifyQQBean.class);
                            ToastUtils.showText(json.getMsg());
                            VerifyQQBean.DataBean data = json.getData();
                            if (data != null) {
                                String token = data.getToken();
                                LogUtils.d("token:" + token);
                                SharedPreUtil.put(mContext, Constants.APPTOKEN, token);
                                startActivity(new Intent(mContext, MainActivity.class));
                                AppManager.getAppManager().finishAllActivity();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(messageReceiver);
        super.onDestroy();
        UMShareAPI.get(this).release();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "登录注册界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "登录注册界面");
    }

    private long exitTime = 0;//记录时间

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtils.showText(getString(R.string.string_click_exit));
            exitTime = System.currentTimeMillis();
        } else {
            ExitStackUtils.getInstance().exit();
        }
    }
}
